package com.yangm.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

public class JsoupUtils {

    public static String regExp = "[\n`~!@#$%^&*()+=|{}';',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。， 、.？]";

    /***
     * @description: 下载微信图片多个地址(多线程)
     * @param: outputFolder
    		   prefix
    		   suffix
    		   urls
     * @return: void
     * @author: ym
     * @date: 21/12/31 17:04
     */
    public static void downloadWeChatImageMultithreading(String outputFolder, String prefix, String suffix
            , Integer[] jumpOver, boolean thread, String... urls) {
        for (String url : urls) {
            ThreadUtil.execute(()->{
                try {
                    downloadWeChatImage(outputFolder,prefix,suffix,url,jumpOver,thread);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    /***
     * @description: 下载微信图片多个地址
     * @param: outputFolder
    		   prefix
    		   suffix
    		   urls
     * @return: void
     * @author: ym
     * @date: 21/12/31 17:04
     */
    public static void downloadWeChatImage(String outputFolder, String prefix, String suffix, Integer[] jumpOver
            , boolean thread, String... urls) {
        for (String url : urls) {
            try {
                downloadWeChatImage(outputFolder,prefix,suffix,url,jumpOver,thread);
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(String.format("执行异常地址：%s",url));
            }
        }
    }

    public static void downloadWeChatImage(String outputFolder, String prefix, String suffix, Integer[] jumpOver
            , boolean thread, List<String> urls) {
        for (String url : urls) {
            try {
                downloadWeChatImage(outputFolder,prefix,suffix,url,jumpOver,thread);
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(String.format("执行异常地址：%s",url));
            }
        }
    }

    /***
     * @description: 下载微信图片
     * @param: outputFolder
    		   prefix
    		   suffix
    		   url
               jumpOver 跳过位置，从0开始，倒数为-
               thread 多线程执行
     * @return: void
     * @author: ym
     * @date: 21/12/31 22:00
     */
    public static void downloadWeChatImage(String outputFolder,String prefix,String suffix,String url
            ,Integer[] jumpOver,boolean thread) throws IOException {
        if(StrUtil.hasEmpty(outputFolder,suffix,url)){
            System.out.println(String.format("参数缺失:{outputFolder=%s}{outputFolder=%s}{outputFolder=%s}"
                    ,outputFolder,suffix,url));
            return;
        }
        Document document = Jsoup.parse(new URL(url),10000000);
        // 根据id获取标题,根据标题生成目录
        Element activityName = document.getElementById("activity-name");
        String title = activityName.text();
        title = title.replaceAll(regExp,"");
        System.out.println(String.format("创建文件夹：%s -- url：%s",title,url));
        String finalOutputFolder = outputFolder + File.separator + title;
        if(!new File(finalOutputFolder).exists()){
            new File(finalOutputFolder).mkdirs();
        }
        finalOutputFolder += File.separator;
        // 保存地址
        FileUtils.writeFile(finalOutputFolder,"地址.txt",new String[]{url});
        // 获取图片div的内容
        Element jsContent = document.getElementById("js_content");
        Elements elements = jsContent.getElementsByTag("img");
        int len = elements.size();
        for (int n = 0; n < elements.size(); n++) {
            // 跳过
            if(jumpOver != null && isJump(jumpOver,len,n)){
                continue;
            }
            // 下载图片
            Element img = elements.get(n);
            String outFileName = finalOutputFolder + prefix + n + suffix;
            String src = img.attr("data-src");
            if(thread){
                // 多线程
                ThreadUtil.execute(()->{
                    try {
                        URL target = new URL(src);
                        // 获取输入流
                        streamToFile(target.openConnection(),outFileName);
                    } catch (IOException e) {
                        System.out.println(String.format("执行异常图片：{名称：%s}{地址：%s}",outFileName,src));
                    }
                });
            }else{
                // 获取输入流
                URL target = new URL(src);
                streamToFile(target.openConnection(),outFileName);
            }

        }
    }

    /***
     * @description: 是否跳过当前位置
     * @param: jumpOver 跳过位置
    		   len 总数
    		   location 当前位置
     * @return: boolean
     * @author: ym
     * @date: 21/12/31 22:06
     */
    public static boolean isJump(Integer[] jumpOver,int len,int location){
        for (Integer integer : jumpOver) {
            if(integer >= 0){
                if(integer == location){
                    return true;
                }
            }else{
                if(integer == (location - len)){
                    return true;
                }
            }
        }
        return false;
    }

    /***
     * @description: 将数据转换为文件
     * @param: urlConnection
    		   outFileName
     * @return: void
     * @author: ym
     * @date: 21/12/31 21:47
     */
    public static void streamToFile(URLConnection urlConnection,String outFileName) {
        try(InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(outFileName)){
            IoUtil.copy(inputStream,fileOutputStream,1024);
            /*int temp = 0;
            while ((temp = inputStream.read()) != -1){
                fileOutputStream.write(temp);
            }*/
        }catch (Exception e){
            System.out.println(String.format("执行异常图片：{名称：%s}{地址：%s}",
                    outFileName,urlConnection.getURL().toString()));
        }
    }

}
